﻿using System;
using System.Text;
using FrameWork.Lib;
using FrameWork.Lib.DataObjects;
using System.Xml.Serialization;

namespace REVISIONMAX30.DataObjects
{
    public class SQLItem : DataObjectBase
    {
        public SQLItem()
        {
        }

        public SQLItem(string pSource, string pSourceType)
            : base(true)
        {
            this.Source = pSource;
            this.SourceType = pSourceType;
            this.SetSourceName();
        }

        public void SetSourceName()
        {
            if (SourceType == "SQLFILE")
            {
                this.SourceName = System.IO.Path.GetFileNameWithoutExtension(this.Source);
            }
            else if (SourceType == "COMMANDTEXT")
            {
                this.SourceName = "Command Text";
            }
            else
            {
                this.SourceName = this.Source;
            }
        }

        public DateTime? Executed { get; set; }
        public DateTime? Expired { get; set; }
        public int ExecutionOrderIndex { get; set; }
        public int Revision { get; set; }
        public Guid? SelectedConnectionStringGUID { get; set; }
        public string SelectedConnectionStringName { get; set; }
        public string SourceName { get; set; }
        public string Source { get; set; }
        public string SourceType { get; set; }
        public string CommandText { get; set; }
        public Result LastExecutionResult { get; set; }

        public Result Execute(EventManager eventManager, ConnectionString connectionString)
        {
            var result = new Result();

            try
            {
                var cb = connectionString.ConnectionStringBuilder;
                result = MySQLDBHandler.ExecuteSQLFileWithMySQLBatch(cb.UserID, cb.Password, cb.Database, Source);
            }
            catch (Exception exc)
            {
                result.AddResult(exc);
            }

            LastExecutionResult = result;
            Executed = DateTime.Now;
            eventManager.AddResult(result);
            return result;
        }

        public void SetConnectionString(ConnectionString pConnectionString)
        {
            this.SelectedConnectionStringName = pConnectionString.Name;
            this.SelectedConnectionStringGUID = pConnectionString.DataObjectGUID;
        }
    }
}

